package com.emns.web.shijie;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.ckfinder.connector.utils.FileUtils;
import com.emns.pojo.Lanmu;
import com.emns.pojo.LanmuZiyuan;
import com.emns.pojo.ShiJie;
import com.emns.service.shijie.ShijieService;
import common.DateUtils;

@Controller
@RequestMapping(value = "/shijie")
public class ShijieController implements ServletContextAware {

	@Autowired
	ShijieService sjs;

	private ServletContext servletContext;
	private String basePath;

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;

	}

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public void uploadFile(String type, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		commonsMultipartResolver.setDefaultEncoding("utf-8");
		String url = "";
		if ("video".equals(type)) {
			basePath = "/home/ghost/workdir/emns/uploadFile";
		} else if ("pic".equals(type)) {
			basePath = servletContext.getRealPath("/") + "userfiles/videoPic";
		}
		System.out.println(basePath);
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multipartRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multipartRequest.getFile((String) iter
						.next());
				if (file != null) {
					String suffix = FileUtils.getFileExtension(file
							.getOriginalFilename());
					System.out.println(suffix);
					String fileName = DateUtils.getFormatDate(new Date(),
							"yyyyMMddHHmmssSSS") + "." + suffix;
					url = saveFileFromInputStream(file.getInputStream(),
							basePath, fileName.toLowerCase());
				}
			}
		}
		response.setStatus(200);
		response.getWriter().append(url);
	}

	private String saveFileFromInputStream(InputStream stream, String path,
			String filename) throws IOException {
		String url = path + "/" + filename;
		FileOutputStream fs = new FileOutputStream(url);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
		return filename;
	}

	@RequestMapping(value = "/addShijie", method = RequestMethod.POST)
	public String add(Model model, ShiJie shijie, int flanmu, int[] lanmu) {
		shijie.setPublishdate(new Date());
		shijie.setReadcount(0);
		shijie.setPlaycount(0);
		shijie.setDownloadcount(0);
		shijie.setShijieId(sjs.insert(shijie));
		for (int i = 0; i < lanmu.length; i++) {
			LanmuZiyuan lmzy = new LanmuZiyuan();
			lmzy.setFirstLanmuId(flanmu);
			lmzy.setSecondLanmuId(lanmu[i]);
			lmzy.setZiyuanId(shijie.getShijieId());
			lmzy.setFlag("2");
			sjs.addLanmuZiyuan(lmzy);
		}
		return "redirect:/shijie_add";
	}

	@RequestMapping(value = "/view")
	public String view(Model model, HttpServletRequest request, Integer id,
			String type) {
		List<Lanmu> lanmu = (List<Lanmu>) request.getSession()
				.getServletContext().getAttribute("secondLanmu");
		List<Lanmu> flanmu = (List<Lanmu>) request.getSession()
				.getServletContext().getAttribute("firstLanmu");
		List<Lanmu> list = new ArrayList<Lanmu>();
		Lanmu firstLanmu = new Lanmu();
		Map<Integer, Boolean> map = sjs.getLanmuZiyuanById(id);
		for (Lanmu tmp : lanmu) {
			Lanmu lm = new Lanmu();
			lm.setId(tmp.getId());
			lm.setName(tmp.getName());
			if (map.containsKey(tmp.getId()))
				lm.setSeleted(true);
			else
				lm.setSeleted(false);
			firstLanmu.setId(tmp.gettLanmuId());
			list.add(lm);
		}
		for (Lanmu tmp : flanmu) {
			if (tmp.getId() == firstLanmu.getId()) {
				firstLanmu = tmp;
				break;
			}
		}
		ShiJie shijie = sjs.getShijieById(id);
		model.addAttribute("model", shijie);
		model.addAttribute("fLanmu", firstLanmu);
		model.addAttribute("sLanmu", list);
		if (type.equals("view")) {
			return "/shijie_view";
		} else {
			return "/shijie_edit";
		}
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(Model model, ShiJie shijie, int flanmu, int[] lanmu) {
		sjs.update(shijie);
		sjs.delLanmuZiyuanById(shijie.getShijieId());
		for (int i = 0; i < lanmu.length; i++) {
			LanmuZiyuan lmzy = new LanmuZiyuan();
			lmzy.setFirstLanmuId(flanmu);
			lmzy.setSecondLanmuId(lanmu[i]);
			lmzy.setZiyuanId(shijie.getShijieId());
			lmzy.setFlag("2");
			sjs.addLanmuZiyuan(lmzy);
		}
		return "redirect:/shijie/query";
	}

	@RequestMapping(value = "/query")
	public String queryAllVideo(Model model,
			@RequestParam(required = false) Integer pageNo,
			@RequestParam(required = false) String title,
			@RequestParam(required = false) String startDate,
			@RequestParam(required = false) String endDate) {
		if (pageNo == null || pageNo < 1)
			pageNo = 1;
		model.addAttribute("page",
				sjs.queryAllVideo(pageNo, title, startDate, endDate));
		model.addAttribute("title", title);
		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);
		return "/shijie_manager";
	}

	@RequestMapping(value = "/delete")
	public String deleteVideo(Model model, Integer[] shijieId,
			@RequestParam(required = false) Integer pageNo,
			@RequestParam(required = false) String title,
			@RequestParam(required = false) String startDate,
			@RequestParam(required = false) String endDate) {
		System.out.println("delete shijieId");
		if (shijieId != null) {
			sjs.delete(shijieId);
		} else {
			System.out.println("shijieId is null");
		}
		return "forward:/shijie/query";
	}
}
